package com.phenix.core.security.handler;

import cn.hutool.core.util.URLUtil;
import com.phenix.core.exception.PhenixGlobalExceptionHandler;
import com.phenix.core.utils.WebUtils;
import com.phenix.defines.response.ResponseMessage;
import com.phenix.tools.string.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 未认证处理自动跳转到登录服务器
 *
 * @author zhenghui
 */
@Slf4j
@Component
public class PhenixAuthenticationEntryPoint implements AuthenticationEntryPoint {

    /**
     * 单点登录认证服务地址
     */
    @Value("${phenix.oauth2.common.auth-server-addr:}")
    private String ssoAuthUrl;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException {

        String referer = request.getHeader(HttpHeaders.REFERER);
        if (StringUtils.isNotBlank(ssoAuthUrl) && StringUtils.isNotBlank(referer)) {
            //web访问需要跳转到sso页面
            StringBuilder ssoBuilder = new StringBuilder(ssoAuthUrl);
            ssoBuilder.append("?redirect_uri=");
            ssoBuilder.append(URLUtil.encode(referer));
            response.sendRedirect(ssoBuilder.toString());
        } else {
            //非web访问返回未鉴权信息
            ResponseMessage resultBody = PhenixGlobalExceptionHandler.resolveException(authException, request.getRequestURI());
            response.setStatus(resultBody.getHttpStatus());
            WebUtils.writeJson(response, resultBody);
        }
    }
}